<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function show_message($message,$actionurl=array(),$target='_self'){
	$CI =& get_instance();
	$CI->load->vars('message',$message);
	$CI->load->vars('actionurl',$actionurl);
	$CI->load->vars('target',$target);
	$message = $CI->load->view('message.php','',true);
	echo $message;exit;
}

function top_redirect($url){
	header("Content-Type: text/html; charset=utf-8");
	$str = '<script type="text/javascript">';
	$str .= 'top.location.href="'.$url.'"';
	$str .= '</script>';
	echo $str;exit;
}

function show_jsonmsg($data){
	if(is_array($data)){
		$return = $data;	
	}else{
		$return = array('status'=>$data);
	}
	echo json_encode($return);exit;
}

function md5pass($pass,$salt){
	return md5(substr(md5($pass),0,10).$salt);
}

function site_aurl($uri = ''){
	$CI =& get_instance();
	$config = $CI->config->config;
	return $CI->config->site_url($config['admin_folder'].'/'.$uri);
}

function get_image_url($url){
	if(substr($url,0,4)=='http'){
		return $url;	
	}else{
		return base_url($url);
	}
}

function get_full_url($url){
	if(substr($url,0,4)=='http'){
		return $url;
	}else{
		return site_url($url);
	}
}

function show_page($pagearr,$search=array()){
	$pagearr['pagenum']=isset($pagearr['pagenum'])&&$pagearr['pagenum']?$pagearr['pagenum']:20;
	$pagearr['currentpage']=$pagearr['currentpage']?$pagearr['currentpage']:1;
	$pagearr['numlinks']=isset($pagearr['numlinks'])&&$pagearr['numlinks']>0?$pagearr['numlinks']:5;
	$pagestr = '';
	$totalpage = ceil($pagearr['totalnum']/$pagearr['pagenum']);
	if($totalpage<2){
		return $pagestr;
	}
	if($pagearr['currentpage']>$pagearr['numlinks']){
		$pagestr .= '<a href="javascript:gotopage(1)">'.lang('first_page').'</a>';
	}
	if($pagearr['currentpage']>1){
		$pagestr .= '<a href="javascript:gotopage('.($pagearr['currentpage']-1).')">'.lang('pre_page').'</a>';
	}
	$prestart = $pagearr['currentpage']-$pagearr['numlinks'];
	$start = $prestart>1?$prestart:1;
	$end = $pagearr['currentpage']+$pagearr['numlinks'];
	$end = $end>$totalpage?$totalpage:$end;
	for($i=$start;$i<$pagearr['currentpage'];$i++){
		$pagestr .= '<a href="javascript:gotopage('.$i.')">'.$i.'</a>';
	}
	$pagestr .= '<strong>'.$i.'</strong>';
	for($i=$pagearr['currentpage'];$i<$end;$i++){
		$pagestr .= '<a href="javascript:gotopage('.($i+1).')">'.($i+1).'</a>';
	}
	if($pagearr['currentpage']<$totalpage){
		$pagestr .= '<a href="javascript:gotopage('.($pagearr['currentpage']+1).')">'.lang('next_page').'</a>';
	}
	if($end<$totalpage){
		$pagestr .= '<a href="javascript:gotopage('.$totalpage.')">'.lang('last_page').'</a>';
	}
	$pagestr .= '<form name="formpage" id="formpage" action="" method="post">';
	$pagestr .= '<input type="hidden" name="currentpage" id="currentpage" value="'.$pagearr['currentpage'].'">';
	foreach($search as $key=>$item){
		$pagestr .= '<input type="hidden" name="'.$key.'" value="'.$item.'">';
	}
	$pagestr .= '</form>';
	return $pagestr;
}

function replacekeyword($keywods,$urls,$content){
	$content = preg_replace("#(<a(.*))(>)(.*)(<)(\/a>)#isU", '\\1-]-\\4-[-\\6', $content);
	$content = @preg_replace("#(^|>)([^<]+)(?=<|$)#sUe", "highlight('\\2', \$keywods, \$urls, '\\1')", $content);
	$content = preg_replace("#(<a(.*))-\]-(.*)-\[-(\/a>)#isU", '\\1>\\3<\\4', $content);
	return $content;
}

function highlight($string, $words, $result, $pre){
	global $replaced;
	$string = str_replace('\"', '"', $string);
		foreach ($words as $key => $word){
			if($replaced[$word] == 1){
				continue;
			}
			$string = preg_replace("#".preg_quote($word)."#", $result[$key], $string,1);
			if(strpos($string, $word) !== FALSE){
				$replaced[$word] = 1;
			}
		}
	return $pre.$string;
}
/*
 * $type:1、文件夹 2、文件
 * $path:1、路径
 */
function dirfile_check($dirfile_items) {
	foreach($dirfile_items as $key => $item) {
		$item_path = $item['path'];
		if($item['type'] == 'dir') {
			if(!dir_writeable(FCPATH.$item_path)) {
				if(is_dir(FCPATH.$item_path)) {
					$dirfile_items[$key]['status'] = 0;
					$dirfile_items[$key]['current'] = '+r';
				} else {
					$dirfile_items[$key]['status'] = -1;
					$dirfile_items[$key]['current'] = 'nodir';
				}
			}else {
				$dirfile_items[$key]['status'] = 1;
				$dirfile_items[$key]['current'] = '+r+w';
			}
		} else {
			if(file_exists(FCPATH.$item_path)) {
				if(is_writable(FCPATH.$item_path)) {
					$dirfile_items[$key]['status'] = 1;
					$dirfile_items[$key]['current'] = '+r+w';
				} else {
					$dirfile_items[$key]['status'] = 0;
					$dirfile_items[$key]['current'] = '+r';
				}
			} else {
				if(dir_writeable(dirname(FCPATH.$item_path))) {
					$dirfile_items[$key]['status'] = 1;
					$dirfile_items[$key]['current'] = '+r+w';
				} else {
					$dirfile_items[$key]['status'] = -1;
					$dirfile_items[$key]['current'] = 'nofile';
				}
			}
		}
	}
	return $dirfile_items;
}

function dir_writeable($dir) {
	$writeable = 0;
	if(!is_dir($dir)) {
		@mkdir($dir, 0777);
	}
	if(is_dir($dir)) {
		if($fp = @fopen("$dir/test.txt", 'w')) {
			@fclose($fp);
			@unlink("$dir/test.txt");
			$writeable = 1;
		} else {
			$writeable = 0;
		}
	}
	return $writeable;
}

function get_suffix($str){
	$arr = explode('.',$str);
	$num = count($arr);
	if($num>0){
		$res = $arr[$num-1];
		return $res;
	}else{
		return false;
	}
}

function splitsql($sql) {
	$sql = str_replace("\r", "\n", $sql);
	$ret = array();
	$num = 0;
	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	foreach($queriesarray as $query) {
		$queries = explode("\n", trim($query));
		$ret[$num] = '';
		foreach($queries as $query) {
			$ret[$num] .= $query[0] == "#" ? NULL : $query;
		}
		$num++;
	}
	return($ret);
}

function mult_to_single($arr,$key='id'){
	$newarr = array();
	foreach($arr as $item){
		$newarr[$item[$key]] = $item;
	}
	return $newarr;
}

function mult_to_idarr($arr,$key='id'){
	$newarr = array();
	foreach($arr as $item){
		$newarr[] = $item[$key];
	}
	return $newarr;
}

function cmp_func($a, $b) {
	global $order;
	if ($a['is_dir'] && !$b['is_dir']) {
		return -1;
	} else if (!$a['is_dir'] && $b['is_dir']) {
		return 1;
	} else {
		if ($order == 'size') {
			if ($a['filesize'] > $b['filesize']) {
				return 1;
			} else if ($a['filesize'] < $b['filesize']) {
				return -1;
			} else {
				return 0;
			}
		} else if ($order == 'type') {
			return strcmp($a['filetype'], $b['filetype']);
		} else {
			return strcmp($a['filename'], $b['filename']);
		}
	}
}



/**
 * 可以统计中文字符串长度的函数
 * @param $str 要计算长度的字符串
 * @param $type 计算长度类型，0(默认)表示一个中文算一个字符，1表示一个中文算两个字符
 */
function abslength($str){
    if(empty($str)){
        return 0;
    }
    if(function_exists('mb_strlen')){
        return mb_strlen($str,'utf-8');
    }
    else {
        preg_match_all("/./u", $str, $ar);
        return count($ar[0]);
    }
}

/**
 * utf-8编码下截取中文字符串,参数可以参照substr函数
 * @param $str 要进行截取的字符串
 * @param $start 要进行截取的开始位置，负数为反向截取
 * @param $len 要进行截取的长度
 */
function utf8_substr($str,$start=0, $len=FALSE, $suffix='...') {
    if(empty($str)){
        return false;
    }
    if (function_exists('mb_substr')){
        if($len !== FALSE) {
            return mb_substr($str,$start,$len,'utf-8').(mb_strlen($str,'utf-8')>$len?$suffix:'');
        }
        else {
            mb_internal_encoding("UTF-8");
            return mb_substr($str,0,$start).(mb_strlen($str,'utf-8')>$start?$suffix:'');
        }       
    }else {
        $null = "";
        preg_match_all("/./u", $str, $ar);
        if($len !== FALSE) {
            return join($null, array_slice($ar[0],$start,$len)).(count($ar[0])>$len?$suffix:'');
        }
        else {
            return join($null, array_slice($ar[0],0,$start)).(count($ar[0])>$start?$suffix:'');
        }
    }
}

/**
 * utf-8编码下是否截取中文字符串
 
 */

function is_substr($str,$start=0) {
	 if (function_exists('mb_substr')){
		mb_internal_encoding("UTF-8");
		if(mb_strlen($str,'utf-8')>$start){
			return true;
		}else{
			return false;
		}
	 }else{
	 	 $null = "";
		  preg_match_all("/./u", $str, $ar);
		  if(count($ar[0])>$start){
			  return true;
		  }else{
			  return false;
		  }
	 }
}

/**
 * 中文截取，支持gb2312,gbk,utf-8,big5  
 *  
 * @param string $str 要截取的字串  
 * @param int $start 截取起始位置  
 * @param int $length 截取长度  
 * @param string $charset utf-8|gb2312|gbk|big5 编码  
 * @param $suffix 是否加尾缀  
 */
function csubstr($str, $start=0, $length=FALSE, $suffix='...', $charset="utf-8"){  
	if($length===FALSE){
		$length=$start;
		$start=0;
	}
   if(function_exists("mb_substr")){
       if(mb_strlen($str, $charset) <= $length) return $str;  
       $slice = mb_substr($str, $start, $length, $charset);  
   }else{
       $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";  
       $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";  
       $re['gbk']          = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";  
       $re['big5']          = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";  
       preg_match_all($re[$charset], $str, $match);  
       if(count($match[0]) <= $length) return $str;  
       $slice = join("",array_slice($match[0], $start, $length));  
   }  
   if($suffix) return $slice.$suffix;
   return $slice;  
}


function array_or($arr){
	$val=0;
	foreach ($arr as $value) {
		$val |= (int)$value;
	}
	return $val;
}
function array_and($arr){
	$val=0;
	foreach ($arr as $value) {
		$val &= (int)$value;
	}
	return $val;
}

function replace_arg($str, $key, $val='', $icase=0){

	if(empty($str)){
		return '?'.$key.'='.urlencode($val);
	}
	if(empty($key)){
		return $str;
	}
	$posfun=$icase?'stripos':'strpos';
	$pos=$posfun($str, '&'.$key.'=');
	if($pos===FALSE){
		$pj='?';
		$pos=$posfun($str, '?'.$key.'=');
	}else{
		$pj='&';
	}
	if($pos===FALSE){
		$pos=$posfun($str, $key.'=');
		if($pos!==0){
			$pos=FALSE;
			return $str.'&'.$key.'='.urlencode($val);
		}else{
			$rstr='?';
		}
	}else{
		$rstr = substr($str, 0, $pos);
	}
	
	if($val!==''){
		$rstr .= $pj.$key.'='.urlencode($val);
	}
	$epos=$posfun($str, '&', $pos+strlen($key)+1);
	if($epos!==FALSE){
		$rstr .= substr($str, $epos);
	}
	return $rstr;
}

/**
 * @return timestamp
 */
function gettime($dateadd, $date=NULL){
	if(is_null($date)){
		$date=new DateTime(date('Y-m-d'));
	}
	if(!is_object($date)){
		if(preg_match('/^\d+$/', $date)){
			$date=new DateTime(date('Y-m-d',$date));
		}else{
			$date=new DateTime($date);
		}
	}
	$ndate=strtotime($date->format('Y-m-d'))+intval($dateadd)*24*60*60;
	//$ndate=date_add($date, DateInterval::createFromDateString(intval($dateadd).' days'));
	return $ndate;
}

/**
 * 抓取网页
 */
function sendpost($url,$data='', $rtype='json'){
	$ch = curl_init();

	// 设置URL和相应的选项
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_FAILONERROR, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_URL, $url );
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_POST, true);
	if(is_array($data)){
		$postdata=http_build_query($data);
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
	}

	// 抓取URL并把它传递给浏览器
	$return=curl_exec($ch);

	//返回状态
	$response = curl_getinfo( $ch );

	// 关闭cURL资源，并且释放系统资源
	curl_close($ch);

	switch ($rtype) {
		case 'json':
			return @json_decode($return,TRUE);
			break;
		case 'xml':
			return @simplexml_load_string($return);
			break;
		default:
			return $return;
			break;
	}	
}

/**
 * 隐藏IP地址段
 */
function maskip($ip, $l=1){
	if(strpos($ip,'.')!==FALSE){
		$dot='.';
	}elseif(strpos($ip, ':')!==FALSE){
		$dot=':';
	}
	$iparr=explode($dot, $ip);
	if($l>count($iparr)){
		$l=$iparr-1;
	}
	return implode($dot,array_slice($iparr, 0,count($iparr)-$l)).str_repeat($dot.'*',$l);
}
